# -*- coding: utf-8 -*-

# Copyright 2003-2007 Jarek Zgoda <jarek.zgoda@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

"""Threads library"""

__revision__ = '$Id: threads.py 11 2008-02-25 21:55:49Z jarek.zgoda $'

import urllib
import threading

import feedparser

import const


class RecommendationsFetcher(threading.Thread):

    def __init__(self, username, queue):
        self.username = username
        self.queue = queue
        threading.Thread.__init__(self)

    def run(self):
        url = const.AUDIOSCROBBLER_FEED_URL % {'username': urllib.quote(self.username)}
        feed = feedparser.parse(url)
        if feed.status == 200:
            for entry in feed.entries:
                term = '%s music' % entry.title.encode('utf-8')
                url = const.TORRENTZ_FEED_URL % \
                    {'term': urllib.quote_plus(term)}
                torrents = feedparser.parse(url)
                if torrents.status == 200:
                    for torrent in torrents.entries:
                        self.queue.put_nowait((torrent.title, torrent.link, entry.title))
        self.queue.put_nowait(('finish', None, None))

